package com.ssy.lingxi.pay.utils;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import jodd.util.StringUtil;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.util.Map;

/**
 * @Description:
 * @Author: HuangJieZhou
 * @Date: 2021/12/20 19:59
 * @Version: 2.0.0
 **/
public class HttpClientUtil {

    public static final Log logger = LogFactory.getLog("httpclient");

    public static String httpReader(String url, String code) {
        logger.info("GetPage:" + url);

        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(url);

        String result = null;
        try {
            client.executeMethod(method);
            int status = method.getStatusCode();
            if (status == HttpStatus.SC_OK) {
                result = method.getResponseBodyAsString();
            } else {
                logger.info("Method failed: " + method.getStatusLine());
            }
        } catch (HttpException e) {
            // 发生致命的异常，可能是协议不对或者返回的内容有问题
            logger.info("Please check your provided http address!");
            e.printStackTrace();
        } catch (IOException e) {
            // 发生网络异常
            logger.info("发生网络异常！");
            e.printStackTrace();
        } finally {
            // 释放连接
            method.releaseConnection();
            method = null;
            client = null;
        }
        return result;
    }

    public static String httpPost(String url, Map<String, Object> paramMap, String code) {
        logger.info("GetPage:" + url);
        logger.info("paramMap:" + paramMap);
        String content = null;
        if (url == null || url.trim().length() == 0){
            return null;
        }
        HttpClient httpClient = new HttpClient();
        //设置header
        httpClient.getParams().setParameter(HttpMethodParams.USER_AGENT, "Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.2) Gecko/20090803 Fedora/3.5.2-2.fc11 Firefox/3.5.2");//

        //代理设置
        //httpClient.getHostConfiguration().setProxy("128.128.176.74", 808);

        PostMethod method = new PostMethod(url);

        if(paramMap != null && paramMap.size() > 0){
            for (Object value : paramMap.keySet()) {
                String key = value + "";
                Object o = paramMap.get(key);
                if (o instanceof String) {
                    method.addParameter(new NameValuePair(key, o.toString()));
                }
                if (o instanceof String[]) {
                    String[] s = (String[]) o;
                    for (String item : s) {
                        method.addParameter(new NameValuePair(key, item));
                    }
                }
            }
        }
        try {

            int statusCode = httpClient.executeMethod(method);

            System.out.println("httpClientUtils::statusCode=" + statusCode);

            logger.info(method.getStatusLine());

            if(StringUtil.isNotEmpty(code)){
                content = new String(method.getResponseBody(), code);
            }else{
                content = new String(method.getResponseBody());
            }

        } catch (Exception e) {
            logger.info("time out");
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
        return content;

    }

    public static String httpPost(String url, Map<String, Object> paramMap) {
        //编码：GB2312
        return HttpClientUtil.httpPost(url, paramMap, "GB2312");
    }

    public static String httpPost(String url, String code) {
        return HttpClientUtil.httpPost(url, null, code);
    }

    public static String httpPost(String url) {
        return HttpClientUtil.httpPost(url, null, "GB2312");
    }

    /**
     * http请求(数字人民币)
     * @param url       路径
     * @param param     参数
     * @return  响应结果
     */
    public static String httpPostDigital(String url, String param){
        HttpRequest httpRequest = HttpUtil.createPost(url).header(Header.USER_AGENT, CcbPayUtil.user_agent);
        httpRequest.charset(CharsetUtil.UTF_8);
        httpRequest.body(param);
        HttpResponse execute = httpRequest.execute();
        return execute.body();
    }
}
